const multer = require('multer')
const path = require('path')
const jwt = require('jsonwebtoken')
const md5 = require('md5')

exports.formatResponse = function(data, msg='', code=200) {
    return { code, msg, data }
}

exports.analysisToken = function(token) {
    token = token.split(' ').length === 1 ? token.split(' ')[0] : token.split(' ')[1]
    return jwt.verify(token, md5(process.env.JWT_SECRET))
}

// 设置上传文件引擎
const storage = multer.diskStorage({
    // 文件存储的位置
    destination: function (req, file, cb) {
        cb(null, path.resolve(__dirname, '../public/uploads'))
    },
    // 处理文件名
    filename: function (req, file, cb) {
        // 获取后缀
        const extname = path.extname(file.originalname)
        // 新文件名
        const newName = `${Date.now()}-${Math.random().toString(36).slice(-6)}${extname}`
        cb(null, newName)
    }
})

exports.uploading = multer({
    storage
})
